import axios from 'axios';
import qs from 'qs';
import { notification } from 'antd';
import router from 'umi/router';

const baseUrl = '';
const http = {
  post: '',
  get: ''
};




function checkStatus(status) {
  if (status === 400) {
    notification.error({
      message: '请求失败',
      description: '请稍后重试'
    });
  }
  if (status === 401) {
    localStorage.clear();
    setTimeout(() => {
      localStorage.clear();
      window.g_app._store.dispatch({
        type: 'login/logout',
      });
      return;
    }, 500)
  }
  // environment should not be used
  if (status === 403) {
    router.push('/exception/403');
    return;
  }
  if (status <= 504 && status >= 500) {
    router.push('/exception/500');
    return;
  }
  if (status >= 404 && status < 422) {
    router.push('/exception/404');
  }
}

function checkMsg(status, val) {
  if (status === 400) {
    notification.error({
      message: '请求失败',
      description: `${val.msg}`
    });
  }
  if (status === 401) {
    localStorage.clear();
    window.g_app._store.dispatch({
      type: 'login/logout',
    });
    return;
  }
  // environment should not be used
  if (status === 403) {
    router.push('/exception/403');
    return;
  }
  if (status <= 504 && status >= 500) {
    router.push('/exception/500');
    return;
  }
  if (status >= 404 && status < 422) {
    router.push('/exception/404');
  }
}

function httpWithMsg(msg) {
  if (msg) {
    notification.error({
      message: '请求失败',
      description: msg
    });
  } else {
    notification.error({
      message: '请求失败',
      description: '请求失败请联系管理员'
    });
  }
}

function checkIsLogin() {
  notification.error({
    message: '请求失败',
    description: '您尚未登录，稍后我们为你跳转到登录页面'
  });
  setTimeout(() => {
    localStorage.clear();
    window.g_app._store.dispatch({
      type: 'login/logout',
    });
    return;
  }, 500)
}


http.postWithStatus = (api, data) => {
  const token = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).token;
  const robotId = (window.localStorage.getItem("robotId")) == undefined ? '' : (window.localStorage.getItem("robotId"));
  const headData = { "Content-Type": "application/json", "token": token, 'robotId': robotId };
  return new Promise((resolve) => {
    axios.post(baseUrl + api, data, { headers: headData }).then((res) => {
      if (!res.data.status) {
        httpWithMsg(res.data.msg)
      }
      if (res.data.data) {
        resolve(res.data.data)
      } else if (res.data === '您尚未登录！') {
        checkIsLogin()
      } else {
        resolve(res.data)
      }
    }).catch((error) => {
      const status = error.name;
      checkStatus(status)
    });
  })
};

http.post = (api, data) => {
  const token = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).token;
  const robotId = (window.localStorage.getItem("robotId")) == undefined ? '' : (window.localStorage.getItem("robotId"));
  const headData = { "Content-Type": "application/json", "token": token, 'robotId': robotId };
  return new Promise((resolve) => {
    axios.post(baseUrl + api, data, { headers: headData }).then((res) => {
      if (res.data.code) {
        httpWithMsg(res.data.msg);
        return checkStatus(res.data.code)
      }
      if (res.data.data) {
        resolve(res.data.data)
      } else if (res.data === '您尚未登录！') {
        checkIsLogin()
      } else {
        resolve(res.data)
      }
    }).catch((error) => {
      const status = error.response.status;
      checkStatus(status)
    });
  })
};

http.postCode = (api, data) => { // 处理400后台的返回内容
  const token = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).token;
  const robotId = (window.localStorage.getItem("robotId")) == undefined ? '' : (window.localStorage.getItem("robotId"));
  const headData = { "Content-Type": "application/json", "token": token, 'robotId': robotId };
  return new Promise((resolve) => {
    axios.post(baseUrl + api, data, { headers: headData }).then((res) => {
      if (res.data.code && res.data.code !== '5000') {
        httpWithMsg(res.data.msg);
        return checkStatus(res.data.code)
      }
      if (res.data.data) {
        resolve(res.data.data)
      } else if (res.data === '您尚未登录！') {
        checkIsLogin()
      } else {
        resolve(res.data)
      }
    }).catch((error) => {
      console.log(error.response.data, error.response.headers, error.config)
      const status = error.response.status;
      checkMsg(status, error.response.data)
    });
  })
};

http.postFormUrlEncoded = (api, data) => {
  const token = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).token;
  const robotId = (window.localStorage.getItem("robotId")) == undefined ? '' : (window.localStorage.getItem("robotId"));
  const headData = { "Content-Type": "application/x-www-form-urlencoded", "token": token, 'robotId': robotId };
  return new Promise((resolve) => {
    axios.post(baseUrl + api, qs.stringify(data), { headers: headData }).then((res) => {
      if (res.data.code) {
        httpWithMsg(res.data.msg);
        return checkStatus(res.data.code)
      }
      if (res.data.data) {
        resolve(res.data.data)
      } else if (res.data === '您尚未登录！') {
        checkIsLogin()
      } else {
        resolve(res.data)
      }
    }).catch((error) => {
      const status = error.response.status;
      checkStatus(status)
    });
  })
};

http.postData = (api, data) => {
  console.log('api', api, data)
  const token = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).token;
  const robotId = (window.localStorage.getItem("robotId")) == undefined ? '' : (window.localStorage.getItem("robotId"));
  const headData = { "Content-Type": "application/json", "token": token, 'robotId': robotId };
  return new Promise((resolve) => {
    axios.post(baseUrl + api, data, { headers: headData }).then((res) => {
      if (res.data.code) {
        httpWithMsg(res.data.msg);
        return checkStatus(res.data.code)
      }
      if (res.data) {
        resolve(res.data)
      } else if (res.data === '您尚未登录！') {
        checkIsLogin()
      } else {
        resolve(res.data)
      }
    }).catch((error) => {
      const status = error.response.status;
      checkStatus(status)
    });
  })
};

http.postWithData = (api, data) => {
  const token = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).token;
  const robotId = (window.localStorage.getItem("robotId")) == undefined ? '' : (window.localStorage.getItem("robotId"));
  const headData = { "Content-Type": "application/json", "token": token, 'robotId': robotId };
  return new Promise((resolve) => {
    axios.post(baseUrl + api, data, { headers: headData }).then((res) => {
      console.log(res)
      if (res.data.code && res.data.code !== 5000) {
        httpWithMsg(res.data.msg);
        return checkStatus(res.data.code)
      }
      if (res.data.data) {
        resolve(res.data)
      } else if (res.data === '您尚未登录！') {
        checkIsLogin()
      } else {
        resolve(res.data)
      }
    }).catch((error) => {
      const status = error.response.status;
      checkStatus(status)
    });
  })
};

http.getTokenData = (api, data) => {
  const token = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).token;
  const robotId = (window.localStorage.getItem("robotId")) == undefined ? '' : (window.localStorage.getItem("robotId"));
  const headData = { "Content-Type": "application/json", "token": token, 'robotId': robotId };
  const params = qs.stringify(data);
  const newUrl = api + "?" + params;
  return new Promise((resolve) => {
    axios.get(baseUrl + newUrl, { headers: headData }).then((res) => {
      console.log(res)
      if (res.data.code) {
        if (res.data.code) {
          httpWithMsg(res.data.msg);
          return checkStatus(res.data.code)
        }
      }
      if (res.data) {
        resolve(res.data)
      } else if (res.data === '您尚未登录！') {
        checkIsLogin()
      } else {
        resolve(res.data)
      }
    }).catch((error) => {
      const status = error.name;
      checkStatus(status)
    });
  })
};


http.getToken = (api, data) => {
  const token = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).token;
  const robotId = (window.localStorage.getItem("robotId")) == undefined ? '' : (window.localStorage.getItem("robotId"));
  const headData = { "Content-Type": "application/json", "token": token, 'robotId': robotId };
  const params = qs.stringify(data);
  const newUrl = api + "?" + params;
  return new Promise((resolve) => {
    axios.get(baseUrl + newUrl, { headers: headData }).then((res) => {
      if (res.data.code) {
        resolve(res.data.data);
        return httpWithMsg(res.data.msg)
      }
      if (res.data.data) {
        resolve(res.data.data)
      } else if (res.data === '您尚未登录！') {
        checkIsLogin()
      } else {
        resolve(res.data)
      }
    }).catch((error) => {
      const status = error.name;
      checkStatus(status)
    });
  })
};

http.get = (api, data) => {
  const params = qs.stringify(data);
  const newUrl = api + "?" + params;
  return new Promise((resolve) => {
    axios.get(baseUrl + newUrl).then((res) => {
      if (res.data.code) {
        httpWithMsg(res.data.msg);
        return checkStatus(res.data.code)
      }
      if (res.data.data) {
        resolve(res.data.data)
      } else if (res.data === '您尚未登录！') {
        checkIsLogin()
      } else {
        resolve(res.data)
      }
    }).catch((error) => {
      const status = error.name;
      checkStatus(status)
    });
  })
};
http.getCode = (api, data) => {
  const params = qs.stringify(data);
  const newUrl = api + "?" + params;
  return new Promise((resolve) => {
    axios.get(baseUrl + newUrl).then((res) => {
      resolve(res.data)
    }).catch((error) => {
      const status = error.name;
      checkStatus(status)
    });
  })
};
http.downloadFile = (api, data) => {
  const token = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).token;
  const robotId = (window.localStorage.getItem("robotId")) == undefined ? '' : (window.localStorage.getItem("robotId"));
  const headData = { "Content-Type": "application/json", "token": token, 'robotId': robotId };
  const params = qs.stringify(data);
  const newUrl = api + "?" + params;
  return new Promise((resolve) => {
    fetch(baseUrl + newUrl, { headers: headData }).then(res => res.blob().then(blob => {
      resolve({ fileBlob: blob, requestRes: res })
    })
    )
  })
};

http.downloadExcel = (api, data) => {
  const token = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).token;
  const robotId = (window.localStorage.getItem("robotId")) == undefined ? '' : (window.localStorage.getItem("robotId"));
  const headData = { "Content-Type": "application/json", "token": token, 'robotId': robotId };
  return new Promise((resolve) => {
    fetch(baseUrl + api, {
      method: 'POST',
      headers: headData,
      body: JSON.stringify(data)
    }).then(res => res.blob().then(blob => {
      resolve({ fileBlob: blob, requestRes: res })
    })
    )
  })
}

export default http;
